<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class FormatApiResponse
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $response = $next($request);

        // 如果$response是一个错误响应，则格式化为JSON
        if ($response->isClientError() || $response->isServerError()) {
            $message = 'Error';
            if(!empty($response->exception)) {
                $message = $response->exception->getMessage();
            }
            $data = [
                'status' => 0,
                'message' => $message,
                'code' => $response->getStatusCode()
            ];
            return new JsonResponse($data, $response->getStatusCode());
        }

        return $response;
    }
}
